<template>
  <!-- 虚拟商品组件 -->
  <div>
    <!-- 商品详情 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        详情信息
      </div>
      <!-- 课程数量 -->
      <label class="flex_y_center margin_top_20">
        <div style="width: 80px; text-align: right">
          <span>*</span>
          {{ lang.goods.total_num }}：
        </div>
        <div style="width: 15%">
          <el-input
            v-model="virtualForm.total_num"
            placeholder="请输入课程数量"
          />
        </div>
      </label>
      <!-- 关联课程 -->
      <div class="margin_top_20" style="display: flex">
        <div
          style="width: 80px; text-align: right; position: relative; top: 5px"
        >
          {{ lang.goods.related_course }}：
        </div>
        <div style="flex-grow: 1">
          <el-button type="primary" @click="getCourseList">
            选择{{ lang.goods.related_course }}
          </el-button>
          <!-- 选择完成的商品列表 -->
          <div v-show="selDoneCrouse.length != 0" class="margin_top_20">
            <el-table :data="selDoneCrouse" height="200" style="width: 75%">
              <el-table-column label="商品名" prop="goods_name" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    @click="delCrouse(scope.row, scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 商品价格信息 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        价格
      </div>
      <!-- 价格 -->
      <label>
        <div class="flex_y_center" style="margin-top: 20px">
          <div style="width: 80px; text-align: right">
            <span>*</span>
            价格：
          </div>
          <div style="width: 15%">
            <el-input
              v-model="virtualForm.goods_price"
              :disabled="virtualForm.is_many_attribute == 'Y'"
              placeholder="请输入价格"
            >
              <template slot="prepend">￥</template>
            </el-input>
          </div>
        </div>
      </label>
      <!-- 积分率 -->
      <label>
        <div class="flex_y_center" style="margin-top: 20px">
          <div style="width: 80px; text-align: right">积分率：</div>
          <div style="width: 15%">
            <el-input
              v-model="virtualForm.goods_points"
              placeholder="请输入积分率"
            >
              <template slot="append">%</template>
            </el-input>
          </div>
        </div>
      </label>
    </div>
    <!-- 提醒 -->
    <div>
      <div
        class="background_gray padding_15 margin_top_20"
        style="border-radius: 5px; font-weight: 600"
      >
        提醒
      </div>
      <!-- 预约提醒 -->
      <div class="margin_top_20 flex_y_center">
        <div style="width: 80px">预约提醒：</div>
        <div>
          <el-radio-group
            v-model="virtualForm.is_remind"
            @change="chooseRemind"
          >
            <el-radio label="N">关闭</el-radio>
            <el-radio label="Y" style="margin: 15px 0">开启</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div v-show="virtualForm.is_remind == 'Y'">
        <!-- 商品提醒 -->
        <div class="margin_top_20" style="display: flex">
          <div style="width: 80px">
            <span>*</span>
            商品提醒：
          </div>
          <div style="width: 92%">
            <el-table :data="virtualForm.goods_remind" width="100%">
              <el-table-column align="center" label="提醒类型">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.remind_type"
                    placeholder="请选择提醒类型"
                    @change="chooseRemindItems(scope.row)"
                  >
                    <el-option label="日周期" value="day" />
                    <el-option label="周周期" value="week" />
                    <el-option label="月周期" value="month" />
                    <el-option label="季周期" value="quarter" />
                    <el-option label="年周期" value="year" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="周期间隔">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remind_value"
                    placeholder="请输入周期间隔"
                    type="Number"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="有效期">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.effective_term"
                    placeholder="请输入有效期"
                    type="Number"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="提醒次数">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.effective_num"
                    placeholder="请输入提醒次数"
                    type="Number"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="
                      virtualForm.goods_remind.length == 1
                        ? $message.error('至少保留一项')
                        : virtualForm.goods_remind.splice(scope.$index, 1)
                    "
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button
              style="margin-top: 10px"
              type="primary"
              @click="addRemindItems"
            >
              添加周期提醒
            </el-button>
          </div>
        </div>
        <!-- 提醒内容 -->
        <div class="margin_top_20" style="display: flex">
          <div class="title_pos" style="width: 80px">
            <span>*</span>
            提醒内容：
          </div>
          <div>
            <div
              v-for="(item, index) of fieldsArr"
              :key="index"
              class="flex_y_center"
              style="margin-bottom: 10px"
            >
              <el-input
                v-model="item.txt"
                placeholder="请输入提醒标题"
                style="width: 50%"
              />
              <div style="margin: 0 10px">文本</div>
              <el-button type="text" @click="fieldsArr.splice(index, 1)">
                删除
              </el-button>
            </div>
            <el-button type="text" @click="fieldsArr.push({ txt: '' })">
              添加提醒周期
            </el-button>
          </div>
        </div>
        <!-- 商品留言 -->
        <div class="margin_top_20 flex_y_center">
          <div style="width: 80px">
            <span>*</span>
            商品留言：
          </div>
          <div>
            <el-input
              v-model="virtualForm.remind_advance"
              placeholder="请输入商品留言"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 商品属性 -->
    <div style="margin-top: 15px">
      <div
        class="background_gray padding_15"
        style="border-radius: 5px; font-weight: 600"
      >
        商品属性
      </div>

      <!-- 营销方式 -->
      <div style="padding: 15px 0; display: flex">
        <!-- 单选 -->
        <div style="width: 80px; text-align: right">
          <span>*</span>
          营销方式：
        </div>
        <div class="flex_direction">
          <el-radio v-model="virtualForm.expire_type" label="sale_at">
            销售日期
          </el-radio>
          <el-radio
            v-model="virtualForm.expire_type"
            label="facture_at"
            style="margin: 15px 0"
          >
            出厂时间
          </el-radio>
          <el-radio v-model="virtualForm.expire_type" label="long_at">
            永久有效
          </el-radio>
        </div>
      </div>
      <!-- 有效期输入框 -->
      <label class="flex_y_center">
        <div style="width: 80px; text-align: right">
          <span v-if="virtualForm.expire_type != 'long_at'">*</span>
          有效期：
        </div>
        <el-input
          v-model="virtualForm.effective_at"
          :disabled="
            virtualForm.expire_type == 'long_at' ||
            virtualForm.expire_type == ''
          "
          placeholder="请输入有效期天数"
          style="width: 15%"
        >
          <template slot="append">天</template>
        </el-input>
      </label>

      <!-- 开售时间 -->
      <div class="flex_y_center margin_top_20">
        <div style="width: 80px; text-align: right">
          <span>*</span>
          开售时间：
        </div>
        <div>
          <el-radio v-model="virtualForm.goods_status" label="on">
            立即开售
          </el-radio>
          <el-radio v-model="virtualForm.goods_status" label="off">
            放入仓库
          </el-radio>
        </div>
      </div>

      <!-- 商品详情 -->
      <div class="margin_top_20" style="display: flex">
        <div style="width: 80px; text-align: right">商品详情：</div>
        <Vue-editor
          :goods-desc="virtualForm.goods_content"
          @sendText="goodsContent"
        />
      </div>
    </div>
    <!-- 添加商品 -->
    <div style="width: fit-content; margin: 20px auto 0">
      <el-button type="primary" @click="searchForm">保存</el-button>
    </div>

    <!-- 代选择课程对话框 -->
    <el-dialog
      :title="'选择' + lang.goods.related_course"
      :visible.sync="dialogCrouse"
    >
      <div>
        <!-- 关键字搜索 -->
        <el-input
          v-model="searchInp"
          placeholder="请输入搜索商品名"
          style="width: 35%"
          @input="getCourseList"
        >
          <el-button slot="prepend" icon="el-icon-search" />
        </el-input>
        <!-- 课程商品展示列表 -->
        <div style="margin-top: 15px">
          <el-table
            ref="goodsTable"
            :data="courseList"
            height="300"
            @row-click="handleCurrentChange"
            @selection-change="selectCrouse"
          >
            <el-table-column type="selection" />
            <el-table-column label="课程名" prop="goods_name" />
          </el-table>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="dialogCrouse = false">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getGoodsList } from '@/api/public'

  export default {
    components: {
      VueEditor: () => import('./editor.vue'),
    },
    // 过滤器
    filters: {
      getName(obj, index) {
        if (obj) {
          var r = parseInt((index - 1) / obj['rowspan'])
          var l = obj['specLen'] || 1
          var key = r % l
          return obj['spec'] && obj['spec'][key] && obj['spec'][key]['cName']
        }
      },
    },
    props: {
      oGoodsDetailsInfo: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        lang: JSON.parse(window.localStorage.getItem('lang')),
        courseList: [], // 存放课程列表
        searchInp: '', // 存放输入的用户关键字
        dialogCrouse: false, // 控制选择课程对话框显示隐藏
        selDoneCrouse: [], // 用于暂存选择的商品，展示使用

        attrs: [],
        batchBool: false,
        batchVal: '',

        fieldsArr: [],

        childType: window.localStorage.getItem('mec_type'),
        virtualForm: {
          is_many_attribute: 'N',
          total_num: '', // 课程数量
          goods_price: '0.00', // 商品价格
          goods_points: 100, // 商品积分率
          is_remind: 'N', // 提醒开关 Y开启 N关闭
          goods_remind: [], // 商品提醒数据
          remind_fields: [], // 到期提醒内容
          remind_advance: '1', // 商品留言
          expire_type: 'long_at', // 营销方式 sale_at销售日期, facture_at出厂日期, long_at长期
          effective_at: '', // 有效期
          goods_status: 'on', // 开售时间
          goods_package: [], // 关联课程
          goods_content: '', // 商品详情
          delivery_method: 'no',
        },
        hint: {
          total_num: '课程数量',
          goods_price: '商品价格',
          expire_type: '营销方式',
          goods_status: '开售时间',
        },
      }
    },
    watch: {
      'virtualForm.expire_type'(newValue) {
        if (newValue == 'long_at') {
          this.virtualForm.effective_at = ''
        }
      },
      // 监听 selDoneCrouse 的变化，执行循环取出选中的课程的id
      selDoneCrouse(newValue) {
        this.virtualForm.goods_package = []
        // 取出选中课程的id取出放入数组，赋值给form中对应属性值
        for (let item of newValue) {
          this.virtualForm.goods_package.push({
            goods_id: item.goods_id,
            goods_name: item.goods_name,
            attrbute_id: item.goods_attr_id || item.attrbute_id,
            // consume_num: item.consume_num,
          })
        }
        // this.$refs.goodsTable.toggleRowSelection(this.selDoneCrouse)
      },
    },
    created() {
      this.assignForm()
    },
    methods: {
      // 将需要的数据赋值到相同属性值上
      assignForm() {
        if (JSON.stringify(this.oGoodsDetailsInfo) != '{}') {
          for (let item in this.virtualForm) {
            if (item == 'goods_attr') {
              this.attrs = this.oGoodsDetailsInfo[item]
            } else if (item == 'goods_package') {
              this.selDoneCrouse = this.oGoodsDetailsInfo[item]
            } else if (
              item == 'remind_fields' &&
              this.oGoodsDetailsInfo.remind_fields != null
            ) {
              for (let item of this.oGoodsDetailsInfo.remind_fields) {
                this.fieldsArr.push({ txt: item })
              }
            } else {
              this.virtualForm[item] = this.oGoodsDetailsInfo[item]
            }
          }
        }
      },

      // 选择课程
      // 获取课程列表
      getCourseList() {
        if (this.courseList.length == 0) {
          const params = {
            goods_type: 'curriculum',
            goods_name: this.searchInp,
          }
          getGoodsList(params).then((res) => {
            this.courseList = res.data
            this.dialogCrouse = true
            this.$nextTick(() => {
              // 判断是否有选择关联商品
              if (this.selDoneCrouse.length != 0) {
                // 进行两层循环对比，如果相同的话，那么就让表格中的该行被选中
                for (let item of this.selDoneCrouse) {
                  for (let itemChild of this.courseList) {
                    if (item.goods_id == itemChild.goods_id) {
                      this.$refs.goodsTable.toggleRowSelection(itemChild, true)
                    }
                  }
                }
              }
            })
          })
        } else {
          this.dialogCrouse = true
        }
      },
      // 选择表格展示商品
      selectCrouse(select) {
        this.selDoneCrouse = select
      },
      // 让选中的行勾选
      handleCurrentChange(row) {
        let bool = true
        for (let item of this.selDoneCrouse) {
          if (item.goods_id == row.goods_id) {
            bool = false
            break
          }
        }
        this.$refs.goodsTable.toggleRowSelection(row, bool)
      },
      // 删除选中的指定的商品列表
      delCrouse(row, index) {
        this.selDoneCrouse.splice(index, 1)
        if (this.courseList.length != 0) {
          this.$refs.goodsTable.toggleRowSelection(row, false)
        }
      },

      // 商品规格
      // 添加商品规格项
      addItem() {
        var obj = {
          pName: '',
          rowspan: 1,
          spec: [{ cName: '' }],
        }
        if (this.attrs.length >= 3) {
          return
        }
        this.attrs.push(obj)
      },
      // 删除规格项
      delSpec(index) {
        this.attrs.splice(index, 1)
      },
      // 清空全部规格
      clearItem() {
        this.attrs = []
      },
      // 添加商品规格值
      addAttrsSpec(index) {
        this.attrs[index].spec.push({ spec: '' })
      },
      // 删除指定规格值
      delItem(fatherIndex, sonIndex) {
        // 判断当前删除的规格值是否在该规格项是最后一个
        if (this.attrs[fatherIndex].spec.length == 1) {
          this.$message.warning(
            this.attrs[fatherIndex].pName + '规格值最少保留一个'
          )
        } else {
          this.attrs[fatherIndex].spec.splice(sonIndex, 1)
        }
      },
      // 控制批量设置价格输入框显示隐藏
      batchClick() {
        this.batchBool = true
        this.batchVal = ''
      },
      // 批量设置规格价格
      batchEndow() {
        if (this.virtualForm.goods_spec.length == 0) {
          this.$message.warning('请先添加规格值')
        } else {
          for (let item of this.virtualForm.goods_spec) {
            item.attribute_item_price = this.batchVal
          }
        }
        this.batchBool = false
      },

      chooseRemind(e) {
        if (e == 'N') {
          this.virtualForm.goods_remind = []
          this.virtualForm.remind_fields = []
          this.virtualForm.remind_advance = ''
        } else {
          this.virtualForm.goods_remind = [
            {
              remind_type: '',
              remind_value: '',
              effective_term: '',
              effective_num: '',
            },
          ]
        }
      },
      // 选择提醒周期类型
      chooseRemindItems(row) {
        switch (row.remind_type) {
          case 'day':
            row.remind_value = 1
            break
          case 'week':
            row.remind_value = 7
            break
          case 'month':
            row.remind_value = 30
            break
          case 'quarter':
            row.remind_value = 90
            break
          case 'year':
            row.remind_value = 365
            break
        }
      },
      // 添加周期提醒项
      addRemindItems() {
        this.virtualForm.goods_remind.push({
          remind_type: '',
          remind_value: '',
          effective_term: '',
          effective_num: '',
        })
      },

      // 检查form表单数据是否有漏输
      searchForm() {
        let formBool = true
        for (let item in this.hint) {
          if (this.virtualForm[item] == '') {
            this.$message.error(this.hint[item] + '未填写')
            formBool = false
            break
          }
        }
        if (!formBool) {
          return
        }

        if (this.virtualForm.expire_type != 'long_at') {
          if (this.virtualForm.effective_at == '') {
            this.$message.error('有效期未输入')
            return
          }
        }
        // 检索预约提醒
        if (this.virtualForm.is_remind == 'Y') {
          for (let item of this.virtualForm.goods_remind) {
            for (let itemChild in item) {
              if (item[itemChild] == '') {
                this.$message.error('商品提醒提醒未填写完整')
                return false
              }
            }
          }
          if (this.fieldsArr.length == 0) {
            this.$message.error('请填写提醒内容')
            return
          } else {
            for (let item of this.fieldsArr) {
              if (item.txt == '') {
                this.$message.error('提醒内容未填写完整')
                return false
              }
            }
            this.virtualForm.remind_fields = []
            for (let item of this.fieldsArr) {
              this.virtualForm.remind_fields.push(item.txt)
            }
          }
          if (this.virtualForm.remind_advance == '') {
            this.$message.error('商品留言未填写')
            return
          }
        }

        if (formBool) {
          this.saveGoods()
        }
      },
      // 将数据传递给父组件
      saveGoods() {
        if (this.virtualForm.goods_package.length != 0) {
          // 防止用户重复点击后，进行多次转JSON字符串操作
          if (typeof this.virtualForm.goods_package != 'string') {
            // 转JSON字符串
            this.virtualForm.goods_package = JSON.stringify(
              this.virtualForm.goods_package
            )
          }
        }
        // 将用户输入的保存，传递给父组件
        this.$emit('sendData', this.virtualForm)
      },
      goodsContent(text) {
        this.virtualForm.goods_content = text
      },
    },
  }
</script>

<style scoped>
  .padding_15 {
    padding: 15px;
  }
  .flex_direction {
    display: flex;
    flex-direction: column;
  }
  span {
    color: red;
  }
  .background_gray {
    background-color: rgb(248, 248, 248);
  }
  .color_shall_gray {
    color: rgba(0, 0, 0, 0.8);
  }
  .margin_top_20 {
    margin-top: 20px;
  }
  .title_pos {
    position: relative;
    top: 7px;
  }
  /**/
  .form_title {
    background: #f8f8f8;
    padding: 10px;
    position: relative;
  }
  .form_title .label {
    color: #999;
  }
  .form_title .delete {
    width: 20px;
    height: 20px;
    line-height: 20px;
    border: 1px solid #ccc;
    border-radius: 50%;
    position: absolute;
    right: 15px;
    top: 50%;
    margin-top: -10px;
    text-align: center;
    color: #fff;
    background: #ccc;
    cursor: pointer;
  }
  .form_list {
    padding: 0 10px;
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-gap: 10px;
    list-style: none;
  }
  .form_group {
    width: 100%;
    border: 1px solid #ccc;
    padding: 10px;
  }
  .form_table {
    margin-top: 10px;
    display: flex;
  }

  /*table*/
  table,
  th,
  td {
    border: 1px solid #f0f0f0;
    border-collapse: collapse;
    text-align: start;
    padding: 14px;
  }
  table {
    width: 100%;
  }
  th {
    background-color: #fafafa;
  }
  tr:hover {
    background-color: #dad8d87e;
  }

  /* input */
  input {
    width: 100%;
    padding: 7px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    color: rgba(0, 0, 0, 0.5);
  }
  .disabled_inp {
    cursor: no-drop;
  }
</style>
